#include "Database.h"
// 初始化数据库连接
void Database::initialize(const std::string& dbPath) {
    std::lock_guard<std::mutex> lock(connectionMutex);
    
    if (dbHandle) {
        throw DatabaseException("Database already initialized");
    }
    databasePath = dbPath;
    int rc = sqlite3_open_v2(dbPath.c_str(), &dbHandle, 
                            SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | 
                            SQLITE_OPEN_FULLMUTEX, nullptr);
    
    if (rc != SQLITE_OK) {
        std::string errMsg = sqlite3_errmsg(dbHandle);
        sqlite3_close(dbHandle);
        dbHandle = nullptr;
        throw DatabaseException("Open database failed: " + errMsg, rc);
    }
    // 设置数据库参数
    execute("PRAGMA journal_mode = WAL");  // 使用WAL日志模式
    execute("PRAGMA synchronous = NORMAL"); // 平衡性能与数据安全
    Logger::log("Database initialized: " + dbPath);
}
// 执行参数化查询
void Database::executePrepared(
    const std::string& sql,
    const std::vector<std::string>& params) 
{
    std::lock_guard<std::mutex> opLock(operationMutex);
    checkConnection();
    sqlite3_stmt* stmt;
    int rc = sqlite3_prepare_v2(dbHandle, sql.c_str(), -1, &stmt, nullptr);
    if (rc != SQLITE_OK) {
        throw DatabaseException("Prepare statement failed: " + std::string(sqlite3_errmsg(dbHandle)), rc);
    }
    // 绑定参数
    for (size_t i = 0; i < params.size(); ++i) {
        rc = sqlite3_bind_text(stmt, i+1, params[i].c_str(), -1, SQLITE_TRANSIENT);
        if (rc != SQLITE_OK) {
            sqlite3_finalize(stmt);
            throw DatabaseException("Bind parameter failed at position " + std::to_string(i+1), rc);
        }
    }
    rc = sqlite3_step(stmt);
    if (rc != SQLITE_DONE) {
        std::string errMsg = sqlite3_errmsg(dbHandle);
        sqlite3_finalize(stmt);
        throw DatabaseException("Execute failed: " + errMsg, rc);
    }
    sqlite3_finalize(stmt);
}
// 查询执行实现
Database::QueryResult Database::executeQuery(
    const std::string& sql,
    const std::vector<std::string>& params)
{
    std::lock_guard<std::mutex> opLock(operationMutex);
    checkConnection();
    QueryResult result;
    char* errMsg = nullptr;
    // 使用包装指针自动释放内存
    auto stmtGuard = std::unique_ptr<sqlite3_stmt, decltype(&sqlite3_finalize)>(
        nullptr, sqlite3_finalize);
    // 准备语句
    sqlite3_stmt* stmt;
    int rc = sqlite3_prepare_v2(dbHandle, sql.c_str(), -1, &stmt, nullptr);
    if (rc != SQLITE_OK) {
        throw DatabaseException("Prepare query failed: " + std::string(sqlite3_errmsg(dbHandle)), rc);
    }
    stmtGuard.reset(stmt);
    // 绑定参数
    for (size_t i = 0; i < params.size(); ++i) {
        rc = sqlite3_bind_text(stmt, i+1, params[i].c_str(), -1, SQLITE_TRANSIENT);
        if (rc != SQLITE_OK) {
            throw DatabaseException("Bind parameter failed at position " + std::to_string(i+1), rc);
        }
    }
    // 获取列名
    const int colCount = sqlite3_column_count(stmt);
    for (int i = 0; i < colCount; ++i) {
        result.columnNames.emplace_back(sqlite3_column_name(stmt, i));
    }
    // 读取数据
    while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
        QueryResult::Row row;
        for (int i = 0; i < colCount; ++i) {
            const char* val = reinterpret_cast<const char*>(sqlite3_column_text(stmt, i));
            row.emplace_back(val ? val : "");
        }
        result.rows.emplace_back(std::move(row));
    }
    if (rc != SQLITE_DONE) {
        throw DatabaseException("Query execution failed: " + std::string(sqlite3_errmsg(dbHandle)), rc);
    }
    return result;
}
// 事务管理实现
void Database::beginTransaction() {
    std::lock_guard<std::mutex> lock(operationMutex);
    if (transactionDepth++ == 0) {
        execute("BEGIN TRANSACTION");
    }
}
void Database::commitTransaction() {
    std::lock_guard<std::mutex> lock(operationMutex);
    if (--transactionDepth == 0) {
        execute("COMMIT");
    }
}
void Database::rollbackTransaction() {
    std::lock_guard<std::mutex> lock(operationMutex);
    transactionDepth = 0;
    execute("ROLLBACK");
}